package cn.chowx.myjfinal.baseinfo;

import java.util.Date;

import org.apache.commons.lang3.math.NumberUtils;
import cn.chowx.myjfinal.baseinfo.model.SpInfo;
import cn.chowx.myjfinal.common.BaseController;
import cn.chowx.myjfinal.help.PageHelp;
import cn.chowx.myjfinal.shiro.UserSeesion;

import com.google.common.base.Strings;

/**
 * sp 
 * @author zcqshine
 *
 */
public class SpInfoController extends BaseController {
	public void index(){
		render("spInfo.html");
	}
	
	/**
	 * 获取 sp 信息列表
	 */
	public void list(){
		setPageHelp();
		String pagejson = SpInfo.DAO.findAll(pageHelp);
		renderJson(pagejson);
	}
	
	/**
	 * 创建,更新,删除 sp 信息
	 */
	public void cud(){
		String oper = getPara("oper");
		String spName = getPara("spName");
		String spContact = getPara("spContact");
		String spPhone = getPara("spPhone");
		String spMail = getPara("spMail");
		String spStatus = getPara("spStatus");
		int status = NumberUtils.toInt(spStatus);
		int id = NumberUtils.toInt(getPara("id"));
		
		SpInfo spInfo = new SpInfo();
		spInfo.set("spName", spName);
		spInfo.set("spContact", spContact);
		spInfo.set("spPhone", spPhone);
		spInfo.set("spMail", spMail);
		spInfo.set("spStatus", status);
		spInfo.set("id", id);
		String msg = null;
		
		if(!Strings.isNullOrEmpty(oper)){
			switch (oper) {
			case PageHelp.OPER_CREATE:
				msg = save(spInfo);
				break;
			case PageHelp.OPER_UPDATE:
				msg = update(spInfo);
				break;
			case PageHelp.OPER_DELETE:
				msg = delete(spInfo);
				break;
			default:
				break;
			}
		}
		renderJson(msg);
	}
	
	/**
	 * 添加 SP 信息
	 * @param spInfo
	 * @return
	 */
	private String save(SpInfo spInfo){
		if(UserSeesion.getCurrentUser() != null){
			spInfo.set("spCreateUser", UserSeesion.getCurrentUser().getInt("id"));
			spInfo.set("spUpdateUser", UserSeesion.getCurrentUser().getInt("id"));
		}else{
			return "保存失败,请重新登录";
		}
		Date now = new Date();
		spInfo.set("spCreateTime", now);
		spInfo.set("spUpdateTime",now);
		
		boolean flag = spInfo.save();
		if(flag){
			return "添加 SP 信息成功";
		}else{
			return "添加 SP 信息失败";
		}
	}
	
	private String update(SpInfo spInfo){
		if(UserSeesion.getCurrentUser() != null){
			spInfo.set("spUpdateUser", UserSeesion.getCurrentUser().getInt("id"));
		}else{
			return "更新失败,请重新登录";
		}
		Date now = new Date();
		spInfo.set("spUpdateTime",now);
		
		boolean flag =spInfo.update();
		if(flag){
			return "更新 SP 信息成功";
		}else{
			return "更新 SP 信息失败";
		}
	}
	
	private String delete(SpInfo spInfo){
		if(spInfo.delete()){
			return "删除失败";
		}else{
			return "删除成功";
		}
	}
}
